<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>养老院护理排班系统 - 三班排班管理</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css">
    <style>
        body {
            background-color: #f5f7fa;
            font-family: "Microsoft YaHei", "微软雅黑", sans-serif;
        }
        .container {
            max-width: 1000px;
            margin-top: 30px;
        }
        .page-header {
            padding: 20px;
            background: linear-gradient(135deg, #43cea2 0%, #185a9d 100%);
            color: white;
            border-radius: 8px;
            margin-bottom: 25px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        }
        .card {
            margin-bottom: 20px;
            border-radius: 8px;
            box-shadow: 0 4px 8px rgba(0,0,0,0.08);
            border: none;
        }
        .card-header {
            background-color: #f0f5ff;
            font-weight: bold;
            color: #185a9d;
            border-bottom: 1px solid #e0e8f5;
            border-radius: 8px 8px 0 0 !important;
            padding: 15px 20px;
        }
        .card-body {
            padding: 20px;
        }
        .form-label {
            font-weight: 500;
            color: #555;
        }
        .form-control, .form-select {
            border-radius: 6px;
            border: 1px solid #ddd;
            padding: 10px 15px;
            margin-bottom: 5px;
        }
        .form-control:focus, .form-select:focus {
            border-color: #43cea2;
            box-shadow: 0 0 0 0.25rem rgba(67, 206, 162, 0.25);
        }
        .btn {
            border-radius: 6px;
            padding: 8px 20px;
            font-weight: 500;
            transition: all 0.3s;
        }
        .btn-primary {
            background-color: #185a9d;
            border-color: #185a9d;
        }
        .btn-primary:hover {
            background-color: #134b83;
            border-color: #134b83;
        }
        .btn-success {
            background-color: #43cea2;
            border-color: #43cea2;
        }
        .btn-success:hover {
            background-color: #38b48f;
            border-color: #38b48f;
        }
        .btn-info {
            background-color: #5bc0de;
            border-color: #5bc0de;
            color: white;
        }
        .btn-info:hover {
            background-color: #46b8da;
            border-color: #46b8da;
            color: white;
        }
        .shift-card {
            border-left: 4px solid #185a9d;
            transition: all 0.3s;
        }
        .shift-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 8px 12px rgba(0,0,0,0.1);
        }
        .shift-card.night {
            border-left-color: #8e44ad;
        }
        .result-container {
            max-height: 500px;
            overflow-y: auto;
        }
        #statusMsg {
            display: none;
            padding: 12px 20px;
            margin-bottom: 20px;
            border-radius: 6px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.08);
        }
        .spinner-border {
            margin-right: 10px;
        }
        .list-group-item {
            border-left: none;
            border-right: none;
            padding: 12px 15px;
        }
        .list-group-item:first-child {
            border-top: none;
        }
        .section-title {
            font-size: 18px;
            color: #185a9d;
            margin-bottom: 15px;
            font-weight: 600;
        }
        .footer {
            text-align: center;
            margin-top: 30px;
            padding: 20px;
            color: #777;
            font-size: 14px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="page-header text-center">
            <h1 class="mb-2">养老院护理三班排班系统</h1>
            <p class="mb-0">将护理员排班分为三班共24小时，实现科学合理的人力资源分配</p>
        </div>
        
        <div id="statusMsg" class="alert"></div>
        
        <div class="row">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <i class="bi bi-calendar-check"></i> 排班生成
                    </div>
                    <div class="card-body">
                        <form id="generateForm">
                            <p class="text-muted mb-3">点击按钮生成基础排班数据，作为三班排班的基础</p>
                            <button type="submit" class="btn btn-primary" id="generateBtn">
                                <span class="spinner-border spinner-border-sm d-none" id="generateSpinner"></span>
                                <i class="bi bi-calendar-plus"></i> 生成基本排班
                            </button>
                        </form>
                    </div>
                </div>
            
                <div class="card">
                    <div class="card-header">
                        <i class="bi bi-calendar-week"></i> 三班排班设置
                    </div>
                    <div class="card-body">
                        <form id="processForm">
                            <div class="mb-3">
                                <label for="startDate" class="form-label">开始日期</label>
                                <input type="date" class="form-control" id="startDate">
                            </div>
                            <div class="mb-3">
                                <label for="periodType" class="form-label">排班周期</label>
                                <select class="form-select" id="periodType">
                                    <option value="day">按日排班</option>
                                    <option value="week">按周排班</option>
                                    <option value="month">按月排班</option>
                                    <option value="quarter">按季度排班</option>
                                    <option value="year">按年排班</option>
                                </select>
                            </div>
                            <div class="mb-3">
                                <label for="periodLength" class="form-label">周期长度</label>
                                <input type="number" class="form-control" id="periodLength" value="1" min="1">
                                <small class="text-muted">例如：2周、3个月等</small>
                            </div>
                            <div class="mb-3">
                                <label for="shiftStartTime" class="form-label">排班开始时间</label>
                                <input type="time" class="form-control" id="shiftStartTime" value="08:00">
                                <small class="text-muted">每天排班的起始时间点</small>
                            </div>
                            <div class="mb-3">
                                <label for="dayNightWeight" class="form-label">白天/黑夜权重比</label>
                                <input type="number" class="form-control" id="dayNightWeight" value="0.618" step="0.001" min="0" max="1">
                                <small class="text-muted">值越大，白班护理员比例越高（默认黄金比0.618）</small>
                            </div>
                            <div class="d-flex flex-wrap">
                                <button type="submit" class="btn btn-success me-2 mb-2" id="processBtn">
                                    <span class="spinner-border spinner-border-sm d-none" id="processSpinner"></span>
                                    <i class="bi bi-clock-history"></i> 处理三班排班
                                </button>
                                <button type="button" class="btn btn-primary mb-2" id="generateAndProcessBtn">
                                    <span class="spinner-border spinner-border-sm d-none" id="comboSpinner"></span>
                                    <i class="bi bi-lightning-charge"></i> 一键生成并处理
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
            
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <i class="bi bi-search"></i> 排班结果查询
                    </div>
                    <div class="card-body">
                        <form id="queryForm">
                            <div class="mb-3">
                                <label for="queryDate" class="form-label">查询日期</label>
                                <input type="date" class="form-control" id="queryDate">
                            </div>
                            <button type="submit" class="btn btn-info" id="queryBtn">
                                <span class="spinner-border spinner-border-sm d-none" id="querySpinner"></span>
                                <i class="bi bi-search"></i> 查询排班结果
                            </button>
                        </form>
                    </div>
                </div>
                
                <div class="card result-card">
                    <div class="card-header">
                        <i class="bi bi-clipboard-data"></i> 查询结果
                    </div>
                    <div class="card-body">
                        <div class="result-container" id="resultContainer">
                            <p class="text-muted text-center">请先查询排班结果</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="footer">
            <p>© 2025 养老院护理排班系统 | 技术支持：养老院信息管理部</p>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.1/font/bootstrap-icons.css"></script>
    <script>
        // 日期格式化函数
        function formatDate(dateStr) {
            const date = new Date(dateStr);
            return date.toISOString().split('T')[0];
        }
        
        // 获取今天日期并设置为默认值
        function setTodayAsDefault() {
            const today = new Date();
            const formattedDate = today.toISOString().split('T')[0];
            document.getElementById('startDate').value = formattedDate;
            document.getElementById('queryDate').value = formattedDate;
        }
        
        // 显示状态消息
        function showStatus(message, isError = false) {
            const statusEl = document.getElementById('statusMsg');
            statusEl.textContent = message;
            statusEl.className = `alert ${isError ? 'alert-danger' : 'alert-success'}`;
            statusEl.style.display = 'block';
            
            // 5秒后自动隐藏
            setTimeout(() => {
                statusEl.style.display = 'none';
            }, 5000);
        }
        
        // 切换加载状态
        function toggleLoading(buttonId, spinnerId, isLoading) {
            const button = document.getElementById(buttonId);
            const spinner = document.getElementById(spinnerId);
            
            button.disabled = isLoading;
            if (isLoading) {
                spinner.classList.remove('d-none');
            } else {
                spinner.classList.add('d-none');
            }
        }
        
        // 渲染排班结果
        function renderScheduleResult(data) {
            const container = document.getElementById('resultContainer');
            
            if (!data || !data.shifts || Object.keys(data.shifts).length === 0) {
                container.innerHTML = '<p class="text-muted text-center">没有找到排班数据</p>';
                return;
            }
            
            let html = `<h5 class="section-title">日期: ${data.date}</h5>`;
            
            // 按班次排序
            const shiftNames = Object.keys(data.shifts).sort();
            
            for (const shiftName of shiftNames) {
                const shift = data.shifts[shiftName];
                const isNight = shiftName.includes('3'); // 假设第三班为夜班
                
                html += `
                    <div class="card shift-card mb-3 ${isNight ? 'night' : ''}">
                        <div class="card-header d-flex justify-content-between align-items-center">
                            <span>${shiftName}</span>
                            <span class="badge bg-primary rounded-pill">${shift.caregivers.length} 名护理员</span>
                        </div>
                        <div class="card-body">
                            <div class="mb-3">
                                <h6 class="section-title">护理员名单:</h6>
                                <p>${shift.caregivers.length > 0 ? shift.caregivers.join(', ') : '暂无护理员'}</p>
                            </div>
                            
                            <h6 class="section-title">时间段安排 (共${shift.slots.length}个):</h6>
                            <ul class="list-group">
                `;
                
                // 显示前5个时间段
                const displaySlots = shift.slots.slice(0, 5);
                for (const slot of displaySlots) {
                    html += `
                        <li class="list-group-item">
                            <div class="d-flex justify-content-between">
                                <strong>${slot.time_slot}</strong>
                                <span class="badge bg-info">${slot.caregiver_id != '-1' ? '已分配' : '未分配'}</span>
                            </div>
                            <div>老人: ${slot.elder}</div>
                            <div>活动: ${slot.activity}</div>
                            <div>护理员: ${slot.caregiver}</div>
                        </li>
                    `;
                }
                
                if (shift.slots.length > 5) {
                    html += `<li class="list-group-item text-center text-muted">... 还有 ${shift.slots.length - 5} 个时间段 ...</li>`;
                }
                
                html += `
                            </ul>
                        </div>
                    </div>
                `;
            }
            
            container.innerHTML = html;
        }
        
        // 页面加载完成后
        document.addEventListener('DOMContentLoaded', function() {
            setTodayAsDefault();
            
            // 生成基本排班
            document.getElementById('generateForm').addEventListener('submit', async function(e) {
                e.preventDefault();
                
                toggleLoading('generateBtn', 'generateSpinner', true);
                
                try {
                    const response = await fetch('/generate_and_save_schedule', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        }
                    });
                    
                    const data = await response.json();
                    
                    if (response.ok) {
                        showStatus('排班生成成功！排班数据已保存到数据库');
                    } else {
                        showStatus(`排班生成失败: ${data.error || '未知错误'}`, true);
                    }
                } catch (error) {
                    showStatus(`发生错误: ${error.message}`, true);
                } finally {
                    toggleLoading('generateBtn', 'generateSpinner', false);
                }
            });
            
            // 处理三班排班
            document.getElementById('processForm').addEventListener('submit', async function(e) {
                e.preventDefault();
                
                toggleLoading('processBtn', 'processSpinner', true);
                
                const params = {
                    start_date: document.getElementById('startDate').value,
                    period_type: document.getElementById('periodType').value,
                    period_length: parseInt(document.getElementById('periodLength').value),
                    shift_start_time: document.getElementById('shiftStartTime').value,
                    day_night_weight: parseFloat(document.getElementById('dayNightWeight').value)
                };
                
                try {
                    const response = await fetch('/process_shift_schedule', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify(params)
                    });
                    
                    const data = await response.json();
                    
                    if (response.ok) {
                        showStatus('三班排班处理成功！护理员已按三班制分配');
                        // 自动查询最新结果
                        document.getElementById('queryDate').value = params.start_date;
                        document.getElementById('queryForm').dispatchEvent(new Event('submit'));
                    } else {
                        showStatus(`三班排班处理失败: ${data.error || '未知错误'}`, true);
                    }
                } catch (error) {
                    showStatus(`发生错误: ${error.message}`, true);
                } finally {
                    toggleLoading('processBtn', 'processSpinner', false);
                }
            });
            
            // 查询排班结果
            document.getElementById('queryForm').addEventListener('submit', async function(e) {
                e.preventDefault();
                
                toggleLoading('queryBtn', 'querySpinner', true);
                
                const queryDate = document.getElementById('queryDate').value;
                
                try {
                    const response = await fetch(`/shift_schedule?date=${queryDate}`);
                    const data = await response.json();
                    
                    if (response.ok) {
                        renderScheduleResult(data);
                    } else {
                        document.getElementById('resultContainer').innerHTML = 
                            `<div class="alert alert-warning">${data.error || '没有找到相应日期的排班数据'}</div>`;
                    }
                } catch (error) {
                    document.getElementById('resultContainer').innerHTML = 
                        `<div class="alert alert-danger">查询出错: ${error.message}</div>`;
                } finally {
                    toggleLoading('queryBtn', 'querySpinner', false);
                }
            });
            
            // 一键生成并处理
            document.getElementById('generateAndProcessBtn').addEventListener('click', async function() {
                toggleLoading('generateAndProcessBtn', 'comboSpinner', true);
                
                const params = {
                    start_date: document.getElementById('startDate').value,
                    period_type: document.getElementById('periodType').value,
                    period_length: parseInt(document.getElementById('periodLength').value),
                    shift_start_time: document.getElementById('shiftStartTime').value,
                    day_night_weight: parseFloat(document.getElementById('dayNightWeight').value)
                };
                
                try {
                    const response = await fetch('/generate_and_process_schedule', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify(params)
                    });
                    
                    const data = await response.json();
                    
                    if (response.ok) {
                        showStatus('排班生成和三班处理成功完成！系统已完成全部处理');
                        // 自动查询最新结果
                        document.getElementById('queryDate').value = params.start_date;
                        document.getElementById('queryForm').dispatchEvent(new Event('submit'));
                    } else {
                        showStatus(`操作失败: ${data.error || '未知错误'}`, true);
                    }
                } catch (error) {
                    showStatus(`发生错误: ${error.message}`, true);
                } finally {
                    toggleLoading('generateAndProcessBtn', 'comboSpinner', false);
                }
            });
        });
    </script>
</body>
</html> 